package com.core;

import com.constant.Constant;
import com.util.FileUtils;
import com.util.HttpUtils;
import com.util.LogUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author YZK
 * @Date 2023/10/18
 * 下载器核心类
 */
public class Downloader {

    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    private ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            Constant.THREAD_NUM,
            Constant.THREAD_NUM,
            0,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(Constant.THREAD_NUM)
    );

    private CountDownLatch countDownLatch = new CountDownLatch(Constant.THREAD_NUM);

    public void download(String url) {
        //获取文件名
        String httpFileName = HttpUtils.getFileName(url);
        //拼接文件下载路径
        httpFileName = Constant.PATH + httpFileName;
        //获取本地文件大小
        long localFileLength = FileUtils.getFileContentLength(httpFileName);
        //获取链接对象
        HttpURLConnection httpURLConnection = null;
        DownloadInfoThread downloadInfoThread = null;
        try {
            httpURLConnection = HttpUtils.getHttpURLConnection(url);
            //获取下载文件的总大小
            int contentLength = httpURLConnection.getContentLength();
            //判断文件是否已经下载过
            //Todo 过后使用MD5进行校验
            if (localFileLength >= contentLength) {
                LogUtils.info("{}文件已经下载完毕，无需重新下载", httpFileName);
                return;
            }
            downloadInfoThread = new DownloadInfoThread(contentLength);
            //将任务交给线程执行，延迟一秒执行，然后每隔一秒执行一次
            scheduledExecutorService.scheduleAtFixedRate(downloadInfoThread, 1, 1, TimeUnit.SECONDS);
            //切分任务
            ArrayList<Future> list = new ArrayList<>();
            split(url, list);
            countDownLatch.await();
            //合并文件
            if (merge(httpFileName)) {
                clearTemp(httpFileName);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("\r");
            System.out.print("下载完成");
            //关闭连接对象
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }

            //关闭
            scheduledExecutorService.shutdownNow();
            //关闭线程池
            poolExecutor.shutdown();
        }
    }

    /**
     * 文件切片
     *
     * @param url        文件地址
     * @param futureList 切片文件的列表
     */
    public void split(String url, List<Future> futureList) {
        //TODO 动态计算文件块的数量，过后以64mb为一块
        try {
            //获取文件下载大小
            long contentLength = HttpUtils.getHttpFileContentLength(url);
            //计算切分后的文件大小
            long size = contentLength / Constant.THREAD_NUM;
            //计算分块个数
            for (int i = 0; i < Constant.THREAD_NUM; i++) {
                //计算下载起始位置
                long startPos = i * size;
                //计算结束位置
                long endPos;
                if (i == Constant.THREAD_NUM - 1) {
                    //下载最后一块
                    endPos = 0;
                } else {
                    endPos = startPos + size;
                }
                //如果不是第一块数据，起始位置要+1
                if (startPos != 0) {
                    startPos++;
                }
                //创建下载任务对象
                DownloadTask downloadTask = new DownloadTask(url, startPos, endPos, i,countDownLatch);

                //提交到线程池
                Future<Boolean> future = poolExecutor.submit(downloadTask);
                futureList.add(future);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /***
     * 文件合并
     * @param fileName 文件名
     * @return boolean
     */
    public boolean merge(String fileName) {
        LogUtils.info("开始合并文件{}", fileName);
        byte[] buffer = new byte[Constant.BYTE_SIZE];
        int len = -1;
        try (RandomAccessFile accessFile = new RandomAccessFile(fileName, "rw")) {
            for (int i = 0; i < Constant.THREAD_NUM; i++) {
                try (BufferedInputStream bis = new BufferedInputStream(
                        Files.newInputStream(Paths.get(fileName + ".temp" + i)))) {
                    while ((len = bis.read(buffer)) != -1) {
                        accessFile.write(buffer, 0, len);
                    }
                }
            }
            LogUtils.info("文件合并完毕");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /***
     * 清楚临时文件
     * @param fileName
     * @return
     */
    public boolean clearTemp(String fileName) {
        for (int i = 0; i < Constant.THREAD_NUM; i++) {
            File file = new File(fileName + ".temp" + i);
            file.delete();
        }
        return true;
    }

}
